/**
 * 音频管理器 - 处理闹钟铃声
 */
class AudioManager {
  constructor() {
    this.audioContext = null;
    this.currentAudio = null;
    this.isPlaying = false;
    this.initAudioContext();
  }

  // 初始化音频上下文
  initAudioContext() {
    try {
      // #ifdef H5
      if (typeof AudioContext !== 'undefined') {
        this.audioContext = new AudioContext();
      } else if (typeof webkitAudioContext !== 'undefined') {
        this.audioContext = new webkitAudioContext();
      }
      // #endif
      
      console.log('音频上下文初始化成功');
    } catch (error) {
      console.error('音频上下文初始化失败:', error);
    }
  }

  // 生成不同类型的闹钟音效
  generateTone(frequency, duration, type = 'sine') {
    return new Promise((resolve) => {
      // #ifdef H5
      if (!this.audioContext) {
        console.warn('音频上下文不可用');
        resolve();
        return;
      }

      try {
        const oscillator = this.audioContext.createOscillator();
        const gainNode = this.audioContext.createGain();

        oscillator.connect(gainNode);
        gainNode.connect(this.audioContext.destination);

        oscillator.frequency.setValueAtTime(frequency, this.audioContext.currentTime);
        oscillator.type = type;

        // 音量渐变效果
        gainNode.gain.setValueAtTime(0, this.audioContext.currentTime);
        gainNode.gain.linearRampToValueAtTime(0.3, this.audioContext.currentTime + 0.1);
        gainNode.gain.exponentialRampToValueAtTime(0.01, this.audioContext.currentTime + duration);

        oscillator.start(this.audioContext.currentTime);
        oscillator.stop(this.audioContext.currentTime + duration);

        oscillator.onended = () => {
          resolve();
        };
      } catch (error) {
        console.error('生成音调失败:', error);
        resolve();
      }
      // #endif

      // #ifndef H5
      // 非H5环境使用系统音效
      setTimeout(() => {
        resolve();
      }, duration * 1000);
      // #endif
    });
  }

  // 播放经典闹钟铃声
  async playClassicAlarm(duration = 10) {
    console.log('播放经典闹钟铃声');
    this.isPlaying = true;

    const startTime = Date.now();
    while (this.isPlaying && (Date.now() - startTime) < duration * 1000) {
      // 高音调
      await this.generateTone(800, 0.5, 'square');
      if (!this.isPlaying) break;
      
      // 低音调
      await this.generateTone(600, 0.5, 'square');
      if (!this.isPlaying) break;
      
      // 短暂停顿
      await new Promise(resolve => setTimeout(resolve, 200));
    }
  }

  // 播放温和提醒音
  async playGentleChime(duration = 8) {
    console.log('播放温和提醒音');
    this.isPlaying = true;

    const startTime = Date.now();
    while (this.isPlaying && (Date.now() - startTime) < duration * 1000) {
      // 和谐的音调序列
      await this.generateTone(523, 0.8, 'sine'); // C5
      if (!this.isPlaying) break;
      
      await this.generateTone(659, 0.8, 'sine'); // E5
      if (!this.isPlaying) break;
      
      await this.generateTone(784, 1.2, 'sine'); // G5
      if (!this.isPlaying) break;
      
      await new Promise(resolve => setTimeout(resolve, 1000));
    }
  }

  // 播放紧急警报音
  async playUrgentAlert(duration = 15) {
    console.log('播放紧急警报音');
    this.isPlaying = true;

    const startTime = Date.now();
    while (this.isPlaying && (Date.now() - startTime) < duration * 1000) {
      // 快速交替的高频音
      for (let i = 0; i < 5 && this.isPlaying; i++) {
        await this.generateTone(1000, 0.2, 'sawtooth');
        await this.generateTone(1200, 0.2, 'sawtooth');
      }
      
      if (!this.isPlaying) break;
      await new Promise(resolve => setTimeout(resolve, 500));
    }
  }

  // 播放自然鸟鸣音
  async playBirdSound(duration = 12) {
    console.log('播放自然鸟鸣音');
    this.isPlaying = true;

    const startTime = Date.now();
    while (this.isPlaying && (Date.now() - startTime) < duration * 1000) {
      // 模拟鸟鸣的频率变化
      const frequencies = [800, 900, 1000, 1100, 1000, 900];
      
      for (let freq of frequencies) {
        if (!this.isPlaying) break;
        await this.generateTone(freq, 0.3, 'sine');
        await new Promise(resolve => setTimeout(resolve, 100));
      }
      
      if (!this.isPlaying) break;
      await new Promise(resolve => setTimeout(resolve, 2000));
    }
  }

  // 停止播放
  stopPlaying() {
    console.log('停止播放音频');
    this.isPlaying = false;
    
    if (this.currentAudio) {
      try {
        this.currentAudio.pause();
        this.currentAudio = null;
      } catch (error) {
        console.error('停止音频失败:', error);
      }
    }
  }

  // 根据铃声类型播放对应音效
  async playRingtone(type = 'classic', duration = 10) {
    // 先停止当前播放
    this.stopPlaying();

    // #ifdef H5
    // H5环境需要用户交互才能播放音频
    if (this.audioContext && this.audioContext.state === 'suspended') {
      try {
        await this.audioContext.resume();
      } catch (error) {
        console.error('恢复音频上下文失败:', error);
      }
    }
    // #endif

    switch (type) {
      case 'classic':
        await this.playClassicAlarm(duration);
        break;
      case 'gentle':
        await this.playGentleChime(duration);
        break;
      case 'urgent':
        await this.playUrgentAlert(duration);
        break;
      case 'bird':
        await this.playBirdSound(duration);
        break;
      default:
        await this.playClassicAlarm(duration);
    }
  }

  // 测试音频功能
  async testAudio() {
    console.log('测试音频功能');
    
    // #ifdef H5
    if (!this.audioContext) {
      console.error('音频上下文不可用，无法测试');
      return false;
    }
    // #endif

    try {
      await this.generateTone(440, 1, 'sine'); // 播放1秒440Hz音调
      console.log('音频测试成功');
      return true;
    } catch (error) {
      console.error('音频测试失败:', error);
      return false;
    }
  }
}

// 创建全局实例
const audioManager = new AudioManager();

export default audioManager;